package com.lzh.exception;


import com.lzh.utils.ResponseResult;
import com.lzh.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    //参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult<?> methodArgumentNotValid(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(fieldError ->
                errorMsg.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(","));
        String errMsg = errorMsg.toString();
        return ResponseResult.error(errMsg);
    }


    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult<?> businessException(BusinessException e){
        log.info("业务异常错误 ==> {}",e.getMessage());
        return ResponseResult.error(e.getErrorCode(),e.getErrorMessage());
    }


    //全局异常保底
    @ExceptionHandler(value = Throwable.class)
    public ResponseResult<?> allException(Throwable e){
        log.error("系统异常错误 ==> {}",e.getMessage());
        return ResponseResult.error(ResultCode.ERROR_DEFAULT.getCode(),ResultCode.ERROR_DEFAULT.getErrorMessage());
    }
}
